// This is where the "user" interrupts handlers should go
// The *must* be declared in "user_interrupts.h"

#include "maindefs.h"
#include <timers.h>
#include "user_interrupts.h"
#include "messages.h"

// A function called by the interrupt handler
// This one does the action I wanted for this program on a timer0 interrupt

void timer0_int_handler()
{
	unsigned int val;
	int length, msgtype;

#if defined(__18F45J10)
	// toggle an LED
	TMR0LED = !TMR0LED;
#endif
#if ADC_ON
	// start A/D Conversion
	ADCON0bits.GO_DONE = 1;
#endif

	// reset the timer
	WriteTimer0(0);


	// try to receive a message and, if we get one, echo it back
	//	length = FromMainHigh_recvmsg(sizeof(val),&msgtype,(void *)&val);
	//	if (length == sizeof(val)) {
	//		ToMainHigh_sendmsg(sizeof(val),MSGT_TIMER0,(void *) &val);
	//	}
}

// A function called by the interrupt handler
// This one does the action I wanted for this program on a timer1 interrupt

void timer1_int_handler()
{
	unsigned int result;
	signed char retval;

#if defined(__18F45J10)
	TMR1LED = !TMR1LED;
#endif

	// read the timer and then its value to main
	//	result = ReadTimer1();
	//	retval = ToMainLow_sendmsg(0,MSGT_TIMER1,(void *) result);
	//	if(retval < 0) {
	// If we get an error, handle it
	//		HANDLE_ERROR(retval);
	//	}

	// reset the timer
	WriteTimer1(0);
}

// A function callled by the interrupt handler
// This one does the action I wanted for this program on a adc interrupt

void adc_int_handler()
{
	unsigned char adc_result[4];
	signed char retval;
	unsigned char cur_channel = ADCON0bits.CHS;
	static unsigned char counter = 0;

#if defined(__18F45J10) // although this should only be occurring on 45j10
	ADCLED = !ADCLED;
#endif

	// Store the ad result bytes, big endian
	adc_result[0] = counter;
	adc_result[1] = ADRESH;
	adc_result[2] = ADRESL;
	adc_result[3] = cur_channel;

	// Send the ad results to msg_q
	retval = ToMainHigh_sendmsg(4, MSGT_ADC, (void *) adc_result);
	if (retval < 0) {
		// If we get an error, call the error handler
		HANDLE_ERROR(retval);
	}

	// Move to next ADC channel
//	if ((counter % 200) == 0) {
		if (cur_channel < 4) {
			ADCON0bits.CHS = cur_channel + 1;
		} else if(cur_channel == 4){
			// Skip from channel 4 to 8 since 5-7 not implemented on 2680
			ADCON0bits.CHS = 8;
		} else if(cur_channel < 10) {
			ADCON0bits.CHS = cur_channel + 1;
		} else {
			ADCON0bits.CHS = 0;
		}
//	}
//	counter++;

}
